package carassius.GUI;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.activation.MimetypesFileTypeMap;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author siebz0r
 */
public class PicturePanel
		extends JPanel
		implements PropertyChangeListener
{
	//<editor-fold defaultstate="collapsed" desc="Fields">
	private BufferedImage _image;
	private BufferedImage _thumbnail;
	private String _imagePath;
	int prevWidth, prevHeight;
	int xOffset, yOffset;
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="Constructors">
	/** Creates new form PicturePanel */
	public PicturePanel()
	{
		initComponents();
		setImage(null);
	}

	public PicturePanel(BufferedImage img)
	{
		_image = img;
		initComponents();
	}
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="Public Properties">
	public BufferedImage getImage() throws NullPointerException
	{
		return _image;
	}

	public String getImagePath()
	{
		return _imagePath;
	}

	public void setImagePath(String imagePath)
	{
		setImagePath((imagePath != null) ? new File(imagePath) : null);
	}

	public boolean setImagePath(File imageLocation)
	{
		try
		{
			if (imageLocation != null && imageLocation.exists())
			{
				_image = ImageIO.read(imageLocation);
				_imagePath = imageLocation.getPath();
				_thumbnail = null;
				repaint();
				return true;
			}
			else
			{
				setImage(null);
			}
		}
		catch (IOException ex)
		{
			System.out.println(ex.toString());
		}
		return false;
	}

	public boolean setImage(BufferedImage image)
	{
		_image = image;
		_imagePath = null;
		_thumbnail = null;
		if (_image == null)
		{
			try
			{
				_image = ImageIO.read(PicturePanel.class.getResourceAsStream("resources/logo.png"));
			}
			catch (IOException ex)
			{
				System.out.println("Could not set default image.");
				System.out.println(ex.toString());
			}
		}
		repaint();
		return true;
	}
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="Protected Methods">
	@Override
	protected void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		if (g != null && getWidth() > 0 && getHeight() > 0)
		{
			if (_image != null
					&& ((prevHeight != getHeight()
					|| prevWidth != getWidth())
					|| _thumbnail == null))
			{
				if (_image.getWidth() <= getWidth() && _image.getHeight() <= getHeight())
				{
					_thumbnail = _image;
				}
				else if (_thumbnail == null)
				{
					//calculate scale factor
					double factor = Math.min(
							(double) getWidth() / (double) _image.getWidth(),
							(double) getHeight() / (double) _image.getHeight());

					//calculate destination image size
					int width = (int) (_image.getWidth() * factor);
					int height = (int) (_image.getHeight() * factor);

					if (width > 0 && height > 0)
					{
						//create thumbnail
						_thumbnail = new BufferedImage(width, height, _image.getType());
						Graphics2D g2 = _thumbnail.createGraphics();
						g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
						g2.drawImage(_image, 0, 0, width, height, null);
					}
					else
					{
						return;
					}
				}
				//calculate offset to center the image
				xOffset = (getWidth() - _thumbnail.getWidth()) / 2;
				yOffset = (getHeight() - _thumbnail.getHeight()) / 2;

				//draw image
				prevHeight = getHeight();
				prevWidth = getWidth();
			}
			if (_thumbnail != null)
			{
				g.drawImage(_thumbnail, xOffset, yOffset, null);
			}
		}
	}
	//</editor-fold>

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setName("Form"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

	@Override
	public void propertyChange(PropertyChangeEvent evt)
	{
		if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())
				&& (evt.getNewValue() instanceof File
				|| evt.getNewValue() == null))
		{
			File image = (File) evt.getNewValue();
			setImagePath(image);
		}
		else if (evt.getNewValue() instanceof File)
		{
			File image = (File) evt.getNewValue();
			if (new MimetypesFileTypeMap().getContentType(image).startsWith("image"))
			{
				setImagePath(image);
			}
			else
			{
				setImage(null);
			}
		}
		else if (evt.getNewValue() instanceof BufferedImage)
		{
			setImage((BufferedImage) evt.getNewValue());
		}
	}
}
